// pages/index/placeDetails/index.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import Utils from '../../../../utils/util';
const $api = require('../../../../request/api').API;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    localeId: '',
    localeName: '',
    address: '',
    createDate: '',
    showUpdataName: '',
    userList: '',
    mainFlag: '',
    helpFlag: 0,
    localeType: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ id }) {
    this.setData({
      localeId: id
    });
    wx.showShareMenu({
      withShareTicket: true
    });
  },
  onShow() {
    if (this.data.localeId) {
      this.localeDetails(this.data.localeId);
    }
  },
  // 解绑场所
  unbindLocale() {
    Dialog.confirm({
      title: '提示',
      message: '确认解绑当前场所吗？'
    }).then(res => {
      let params = {
        id: this.data.localeId,
        state: -1
      };
      app.globalData.refreshBeeperList = true;
      $api.unbindLocale(params).then(res => {
        if (res.data.status === 0) {
          Toast('解绑成功');
          const pages = getCurrentPages().at(-2);
          pages.localeList();
          app.eventBus.emit('refreshBeeperList');
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1000);
        }
      });
    });
  },
  // 去紧急联系人页面
  toEmergencyContact() {
    wx.navigateTo({
      url: '/subcontract/equipment/pages/emergencyContact/index?localeId=' + this.data.localeId
    });
  },
  async localeDetails(id) {
    let res = await $api.localeDetails({ id });
    res = res.data.data;
    this.setData({
      localeName: res.localeName,
      address: res.address,
      createDate: res.createDate,
      userList: res.list,
      mainFlag: res.mainFlag,
      helpFlag: res.helpFlag,
      localeType: res.localeType
    });
  },
  // 点击添加成员
  clickAdd() {
    Toast('此功能正在开发中..');
  },
  // 去用户用户列表页面
  toUserList() {
    if (this.data.mainFlag == 0) return;
    wx.navigateTo({
      url: '/subcontract/equipment/pages/userList/index?id=' + this.data.localeId
    });
  },
  async handleHelpFlagChange(e) {
    await $api.setHelpFlag({ helpFlag: e.detail, localeId: this.data.localeId });
    this.setData({
      helpFlag: e.detail
    });
  },

  /**
   * 用户点击右上角分享
   * 携带参数：场所id 当前时间戳
   * 被分享页，进页面先判断十分钟时间，再判断是否已注册（根据openId），
   */
  onShareAppMessage() {
    console.log('分享的场所id', this.data.localeId);
    let startTime = Utils.formatDate(new Date());
    return {
      title: '快来一起使用智慧呼叫', // 分享出的卡片标题
      path: '/subcontract/equipment/pages/share/index?localeId=' + this.data.localeId + '&startTime=' + startTime, // 他人通过卡片进入小程序的路径，可以在后面拼接URL的形式带参数
      imageUrl: 'https://pic.kanglailab.com/common/beeper.png' // 分享出去的图片，默认为当前页面的截图。图片路径可以是本地文件路径或者网络图片路径。支持PNG及JPG。
    };
  },
  // 打开修改昵称弹框
  openUpdataName() {
    this.setData({
      showUpdataName: true
    });
  },
  // 关闭修改昵称弹框
  closeUpdataName() {
    this.setData({
      showUpdataName: false
    });
  },
  // 输入绑定
  equipNickNameInput(e) {
    let value = e.detail.value;
    this.setData({
      equipNickName: value
    });
  },
  // 修改昵称
  UpdataName() {
    const { equipNickName, localeId } = this.data;
    if (equipNickName == '') {
      Toast('请输入昵称');
      return;
    }
    let params = {
      localeId,
      localeNickName: equipNickName
    };
    $api
      .setNickName(params)
      .then(res => {
        if (res.data.status == 0) {
          wx.showToast({
            title: '设置昵称成功'
          });
          this.setData({
            showUpdataName: false,
            localeName: equipNickName
          });

          // 给场所列表页面的修改名字
          const pages = getCurrentPages();
          const placeListPage = pages.find(item => item.route == 'subcontract/equipment/pages/placeList/index');
          if (placeListPage) {
            const { localeList } = placeListPage.data;
            const target = localeList.find(item => item.id == localeId);
            target.name = equipNickName;
            placeListPage.setData({
              localeList
            });
          }

          // 操作home页面给场所修改名字
          const homePage = pages.find(item => item.route == 'pages/equipment/index');
          const { data } = homePage;
          const target = data.localeList.find(item => item.id == localeId);
          target.name = equipNickName;
          if (data.localeId == localeId) {
            homePage.setData({
              localeName: equipNickName
            });
          }
          homePage.setData({
            localeList: data.localeList
          });
          // setTimeout(() => {
          //   this.setData({
          //     showUpdataName: false
          //   })
          //  wx.navigateBack()
          // }, 1000);
        }
      })
      .catch(err => {
        console.log(err);
      });
  }
});
